package com.youboy.oauth.provider.impl;

import java.util.Arrays;
import java.util.List;

import com.youboy.oauth.common.OAuthParameters;
import com.youboy.oauth.consumer.OAuthConsumerService;
import com.youboy.oauth.model.InvalidRequestVerbException;
import com.youboy.oauth.model.MissingRequiredParameterException;
import com.youboy.oauth.model.OAuthRequest;
import com.youboy.oauth.model.UnsupportedParameterException;
import com.youboy.oauth.nonce.OAuthNonceService;
import com.youboy.oauth.provider.OAuthProvider;
import com.youboy.oauth.provider.OAuthProviderSupport;
import com.youboy.oauth.signature.OAuthSignatureFactory;
import com.youboy.oauth.token.OAuthTokenService;

/**
 * 
 * @author loudyn
 * 
 */
public class OAuth10aProvider extends OAuthProviderSupport {

	private static final List<String> ALLOW_VERBS = Arrays.asList(new String[] { "GET", "POST" });
	public static final String SUPPORT_OAUTH_VERSION = "1.0";

	public OAuth10aProvider(OAuthRequest oauthRequest, OAuthConsumerService oauthConsumerService,
							OAuthTokenService oauthTokenService, OAuthNonceService oauthNonceService,
							OAuthSignatureFactory oauthSignatureFactory) {
		super(oauthRequest, oauthConsumerService, oauthTokenService, oauthNonceService, oauthSignatureFactory);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youboy.oauth.provider.OAuthProvider#getVersion()
	 */
	@Override
	public final String getVersion() {
		return SUPPORT_OAUTH_VERSION;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youboy.oauth.provider.OAuthProvider#exceptOAuthRequest()
	 */
	@Override
	public OAuthProvider exceptOAuthRequest() throws UnsupportedParameterException,
														MissingRequiredParameterException,
														InvalidRequestVerbException {

		getOAuthRequest().validateParameters();

		String verb = getOAuthRequest().getVerb();
		if (!ALLOW_VERBS.contains(verb)) {
			throw new InvalidRequestVerbException(String.format("%s verb is not supported", verb));
		}

		String oauthVersion = getOAuthRequest().getOAuthParameters().get(OAuthParameters.OAUTH_VERSION.asString());
		if (null == oauthVersion) {
			throw new MissingRequiredParameterException(
											String.format("Required %s parameter!", OAuthParameters.OAUTH_VERSION.asString()));
		}

		if (!SUPPORT_OAUTH_VERSION.equals(oauthVersion)) {
			throw new UnsupportedParameterException(String.format("the oauthVersion(%s) is not supported", oauthVersion));
		}

		return this;
	}
}
